<?php
/**
*	短信sms
*/
namespace Rainrock\Framework\Chajian;


use Rainrock\Framework\kernel\core\Chajian;
use Rainrock\Framework\kernel\base\Base;


class smsChajian extends Chajian{
	
	public static function get($type='')
	{
		if(!$type)$type = Base::getConfig('sms_type');
		if(!$type)$type = 'yunpian';
		$obj	= Chajian::getObj('sms'.$type.'');
		$obj->setSmstype($type);
		return $obj;
	}
	
	protected $smstype = '', $codetpl = '',$smssign = '';
	
	protected function initChajian() 
	{ 
		$this->codetpl = Base::getConfig('sms_codetpl'); 
		$this->smssign = Base::getConfig('sms_sign'); 
	}

	/**
	*	获取验证码
	*/
	public final function getCode($mobile, $device, $type, $cont = '', $sign='')
	{
		$key 	= ''.$mobile.'_'.$device.'_'.$type.'';
		$cache 	= $this->c('cache');
		$oval	= $cache->get($key);
		if($oval){
			$otime 	= floatval($oval['time']);
			$sj		= time() - $otime;
			if($sj < 60)return $this->returnerror('获取太快，请'.(60-$sj).'秒再试', 201, array(
				'time' => 60-$sj
			));
		}
		
		$code 	= rand(100000,999999);
		$bool	= $cache->set($key, array(
			'code' => $code,
			'time' => time()
		), 60*5);
		if(!$bool)return $this->returnerror('cache不能使用');
		if(!$cont)$cont 	= $this->codetpl;
		if(!$cont)$cont 	= '您短信验证码为：#code#，请勿将验证码提供给他人。';
		
		$barr = $this->send($mobile, $cont, $sign, array(
			'code' => $code
		));
		if(!$barr['success'])$cache->del($key);
		return $barr;
	}
	
	/**
	*	验证是不是对的
	*/
	public final function checkCode($mobile, $device, $type, $code)
	{
		$key 	= ''.$mobile.'_'.$device.'_'.$type.'';
		$cache 	= $this->c('cache');
		$oval	= $cache->get($key);
		if(!$oval)return $this->returnerror('验证码错误了');
		$ycode 	= $this->arrvalue($oval, 'code');
		if($code != $ycode)return $this->returnerror('验证码错误啦');
		$cache->del($key);
		return $this->returnsuccess();
	}
	
	/**
	*	调用的需重写
	*/
	public function sendsms($mobile, $cont, $sign, $params)
	{
		return $this->returnerror('短信类型'.$this->smstype.'未开发');
	}
	
	/**
	*	发送
	*/
	public final function send($mobile, $cont, $sign, $params=array())
	{
		if(1==2 && Base::getConfig('systype')=='dev' && $this->smstype !='wxqy'){
			return $this->returnsuccess(array(
				'cont' 	=> $cont,
				'sign' 	=> $sign,
				'params' => $params,
				'smstype' => $this->smstype,
			));
		}
		if(!$sign)$sign = $this->smssign;
		if(!$sign)return $this->returnerror('未设置短信签名');
		foreach($params as $k=>$v)$cont = str_replace('#'.$k.'#', $v, $cont);
		return $this->sendsms($mobile, $cont, $sign, $params);
	}
	
	/**
	*	设置类型
	*/
	public final function setSmstype($val)
	{
		$this->smstype = $val;
		return $this;
	}
	
	/**
	*	设置验证码模版
	*/
	public final function setCodetpl($val)
	{
		$this->codetpl = $val;
		return $this;
	}
}